package com.studentbook.servlet;

import com.studentbook.bean.StudentContact;
import com.studentbook.service.StudentContactService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 添加联系人Servlet
 */
@WebServlet("/addContact")
public class AddContactServlet extends HttpServlet {
    private StudentContactService contactService = new StudentContactService();
    
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置请求和响应编码
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        
        // 获取请求参数
        String studentId = request.getParameter("studentId");
        String name = request.getParameter("name");
        String grade = request.getParameter("grade");
        String contactInfo = request.getParameter("contactInfo");
        
        // 参数校验
        if (studentId == null || studentId.trim().isEmpty() ||
            name == null || name.trim().isEmpty()) {
            request.setAttribute("message", "学号和姓名不能为空！");
            request.getRequestDispatcher("/add.jsp").forward(request, response);
            return;
        }
        
        // 创建联系人对象
        StudentContact contact = new StudentContact(studentId, name, grade, contactInfo);
        
        // 添加联系人
        boolean success = contactService.addContact(contact);
        
        if (success) {
            // 添加成功，重定向到联系人列表页面
            response.sendRedirect(request.getContextPath() + "/listContacts");
        } else {
            // 添加失败，返回添加页面并显示错误信息
            request.setAttribute("message", "添加失败，学号可能已存在！");
            request.getRequestDispatcher("/add.jsp").forward(request, response);
        }
    }
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 转发到添加联系人页面
        request.getRequestDispatcher("/add.jsp").forward(request, response);
    }
}